import tkinter as tk
from tkinter import messagebox

# 定义一个空字典用于存储已注册的用户名和密码
registered_users = {}


def register():
    username = username_entry.get()
    password = password_entry.get()

    if username == "" or password == "":
        messagebox.showerror("错误", "用户名和密码不能为空。")
        return

    if username in registered_users:
        messagebox.showerror("错误", "该用户名已被注册，请重新选择用户名。")
    else:
        registered_users[username] = password
        messagebox.showinfo("成功", "注册成功！")


def login():
    username = username_entry.get()
    password = password_entry.get()

    if username == "" or password == "":
        messagebox.showerror("错误", "用户名和密码不能为空。")
        return

    if username not in registered_users:
        messagebox.showerror("错误", "该用户名未注册，请先注册。")
    elif registered_users[username] == password:
        messagebox.showinfo("成功", "登录成功！")
    else:
        messagebox.showerror("错误", "密码错误，请重新登录。")


# 创建主窗口
root = tk.Tk()
root.title("注册和登录")

# 创建用户名标签、输入框
username_label = tk.Label(root, text="用户名：")
username_label.grid(row=0, column=0, padx=10, pady=5)
username_entry = tk.Entry(root)
username_entry.grid(row=0, column=1, padx=10, pady=5)

# 创建密码标签、输入框
password_label = tk.Label(root, text="密码：")
password_label.grid(row=1, column=0, padx=10, pady=5)
password_entry = tk.Entry(root, show="*")
password_entry.grid(row=1, column=1, padx=10, pady=5)

# 创建注册按钮
register_button = tk.Button(root, text="注册", command=register)
register_button.grid(row=2, column=1, padx=10, pady=10)

# 创建登录按钮
login_button = tk.Button(root, text="登录", command=login)
login_button.grid(row=2, column=0, padx=10, pady=10)

# 运行主循环
root.mainloop()